//
//  BuyHouseViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "BuyHouseViewController.h"

#import "BuyHouseCell.h"
#import "RentHouseCell.h"
#import "ZFDetViewController.h"
#import "BHDetViewController.h"
#import "SearchViewController.h"
@interface BuyHouseViewController ()<UITableViewDelegate,UITableViewDataSource,BMKLocationServiceDelegate>{
    UILabel *labLine;
    UIView *view1;
    UIView *view2;
    NSMutableArray *array;
    NSMutableArray *datas;
    BMKLocationService *location;
    CGFloat lat;
    CGFloat lng;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableDictionary *dic;

@end

@implementation BuyHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadNav];
    [self loadMFView];
    [self loadZFView];
    _dic = [NSMutableDictionary dictionary];
    array = [NSMutableArray array];
    datas = [NSMutableArray array];
    //[user setObject:@"19" forKey:@"userid"];
    [_dic setObject:@"aaa" forKey:@"tag"];
    view2.hidden = YES;
    [self loadData];
    [self loadData2];
    //[self loadMap];
    
}

- (void)loadMap{
    location = [[BMKLocationService alloc] init];
    [location startUserLocationService];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    location.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    location.delegate = nil;
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    [location stopUserLocationService];
    
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UIButton *btnL = [UIButton buttonWithType:UIButtonTypeCustom];
    btnL.frame = CGRectMake(ScreenWidth/2-50, 30, 40, 20);
    [btnL setTitle:@"买房" forState:UIControlStateNormal];
    [btnL setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnL addTarget:self action:@selector(clickL) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnL];
    
    UIButton *btnR = [UIButton buttonWithType:UIButtonTypeCustom];
    btnR.frame = CGRectMake(ScreenWidth/2+10, 30, 40, 20);
    [btnR setTitle:@"租房" forState:UIControlStateNormal];
    [btnR setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnR addTarget:self action:@selector(clickR) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnR];
    
    labLine = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2-50, 55, 40, 4)];
    labLine.backgroundColor = [UIColor redColor];
    labLine.layer.cornerRadius = 5.0;
    [view addSubview:labLine];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSearch.frame = CGRectMake(ScreenWidth-40, 24, 40, 40);
    [btnSearch setImage:[UIImage imageNamed:@"搜索-(1)"] forState:UIControlStateNormal];
    [btnSearch addTarget:self action:@selector(clickSearch) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnSearch];
    
}

- (void)clickL{
    [UIView animateWithDuration:0.3 animations:^{
        labLine.frame = CGRectMake(ScreenWidth/2-50, 55, 40, 4);
    }];
    [_dic setObject:@"aaa" forKey:@"tag"];
    [_tableView reloadData];
}

- (void)clickR{
    [UIView animateWithDuration:0.3 animations:^{
        labLine.frame = CGRectMake(ScreenWidth/2+10, 55, 40, 4);
    }];
    [_dic setObject:@"sss" forKey:@"tag"];
    [_tableView reloadData];
}

- (void)clickSearch{
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}

//买房页面
- (void)loadMFView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-49-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 171)];
    _tableView.tableHeaderView = headView;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 171)];
    imageView.image = [UIImage imageNamed:@"58f4bdbb95ee2_1024"];
    [headView addSubview:imageView];
    
}
//租房页面
- (void)loadZFView{
    view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    view2.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view2];
    
}

#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *str = [_dic objectForKey:@"tag"];
    if ([str isEqualToString:@"aaa"]) {
        return array.count;
    }
    return datas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [_dic objectForKey:@"tag"];
    if ([str isEqualToString:@"aaa"]) {
        static NSString *cellId = @"Cell1";
        BuyHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BuyHouseCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.labTit1.layer.cornerRadius = 5.0;
        cell.labTit1.layer.borderWidth = 0.5;
        cell.labTit1.layer.borderColor = COLOR_RGB(17, 100, 253, 1).CGColor;
        
        cell.labTit2.layer.cornerRadius = 5.0;
        cell.labTit2.layer.borderWidth = 0.5;
        cell.labTit2.layer.borderColor = COLOR_RGB(17, 100, 253, 1).CGColor;
        NSDictionary *dic = array[indexPath.row];
        cell.labName.text = [dic objectForKey:@"title"];
        
        cell.labDet.text = [dic objectForKey:@"address"];
        
        cell.labPrice.text = [NSString stringWithFormat:@"%li元/㎡",[[dic objectForKey:@"price"] integerValue]];
        NSString *state = [dic objectForKey:@"labelling"];
        NSArray *arr = [state componentsSeparatedByString:@"|"];
        cell.labTit1.text = arr[0];
        cell.labTit2.text = arr[1];
        cell.labKM.text = [NSString stringWithFormat:@"%likm",[[dic objectForKey:@"km"] integerValue]];
        cell.labMJ.text = [NSString stringWithFormat:@"建面 %@㎡",[dic objectForKey:@"qujian"]];
        //图片数组
        NSString *pic = [dic objectForKey:@"homepic"];
        NSArray *imgs = [pic componentsSeparatedByString:@"|"];
        NSString *image0 = [imgs objectAtIndex:0];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],image0];
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"timg-(6)"]];
        
        return cell;
    }else{
        static NSString *cellId = @"Cell2";
        RentHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"RentHouseCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = datas[indexPath.row];
        //图片数组
        NSString *pic = [dic objectForKey:@"pic"];
        NSArray *imgs = [pic componentsSeparatedByString:@"|"];
        NSString *image0 = [imgs objectAtIndex:0];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],image0];
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"timg-(6)"]];
        
        cell.labTitle.text = [dic objectForKey:@"title"];
        cell.labArea.text = [dic objectForKey:@"community"];
        cell.labHX.text = [dic objectForKey:@"room"];
        cell.labRentState.text = [dic objectForKey:@"mode"];
        NSString *price = [NSString stringWithFormat:@"%li元/月",[[dic objectForKey:@"mnthly"] integerValue]];
        cell.labPrice.text = price;
        NSString *juli = [NSString stringWithFormat:@"%likm",[[dic objectForKey:@"km"] integerValue]];
        cell.labJuLi.text = juli;
        
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [_dic objectForKey:@"tag"];
    if (![user objectForKey:@"userid"]) {
        NSLog(@"aaaa");
    }
    
    
    if ([str isEqualToString:@"aaa"]) {
        NSDictionary *dic = array[indexPath.row];
        NSString *hId = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"id"] integerValue]];
        
        BHDetViewController *det = [[BHDetViewController alloc] init];
        det.hid = hId;
        
        [self.navigationController pushViewController:det animated:YES];
    }else{
        NSDictionary *op = datas[indexPath.row];
        NSString *houseId = [NSString stringWithFormat:@"%li",[[op objectForKey:@"id"] integerValue]];
        [user setObject:@"19" forKey:@"userid"];
        ZFDetViewController *det = [[ZFDetViewController alloc] init];
        det.hID = houseId;
        [self.navigationController pushViewController:det animated:YES];
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [_dic objectForKey:@"tag"];
    if ([str isEqualToString:@"aaa"]) {
        return 110.0;
    }else{
        return 116.0;
    }
    
}

//头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 39, ScreenWidth, 0.5)];
    lab.backgroundColor = [UIColor grayColor];
    [view addSubview:lab];
    
    NSArray *titles = @[@"区域",@"价格",@"户型",@"更多"];
    for (NSInteger i = 0; i<titles.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(ScreenWidth/4*i, 0, ScreenWidth/4, 40);
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"多边形-2"] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        //设置文字在左，图片在右
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn.imageView.image.size.width, 0, btn.imageView.image.size.width)];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.frame.size.width+5, 0, -btn.titleLabel.frame.size.width)];
        
        btn.tag = i;
        [btn addTarget:self action:@selector(clicks:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn];
        
    }
    
    return view;
}
//按钮点击事件
- (void)clicks:(UIButton *)btn{
    if (btn.tag == 0) {
        
    }else if (btn.tag == 1){
        
    }else if (btn.tag == 2){
        
    }else{
        
    }
}
//头视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40.0;
}
//买房
- (void)loadData{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    [parmas setObject:@"1" forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Bridalchamber/chamber",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"买房res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            array = [responseObject objectForKey:@"result"];
        }
        
        [_tableView reloadData];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}
//租房
- (void)loadData2{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    [parmas setObject:@"1" forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Rentout/renthous",urlHead];
    [manager GET:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"租房res:%@",responseObject);
        datas = [responseObject objectForKey:@"result"];
        NSLog(@"datascount:%li",datas.count);
        
        [_tableView reloadData];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
